<template>
  <div class="common-wrapper">
    <div class="common-title">车台数据</div>
    <div class="common-main">
      <el-form
        ref="search"
        class="common-search"
        :model="search"
        :inline="true"
        :rules="searchRules"
      >
        <el-form-item>
          <el-select
            v-model="search.org"
            placeholder="选择组织"
            size="small"
            clearable
            style="width:120px"
          >
            <el-option
              v-for="(item, index) in orgOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="search.cj"
            placeholder="选择车间"
            size="small"
            style="width:120px"
            clearable
          >
            <el-option
              v-for="(item, index) in cjOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="gongxu" :show-message="false">
          <el-select
            v-model="search.gongxu"
            placeholder="选择工序"
            size="small"
            style="width:120px"
            clearable
            @change="changeGX"
          >
            <el-option
              v-for="(item, index) in gxOption"
              :key="index"
              :label="item['key_value']"
              :value="item['key_value']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="params" :show-message="false">
          <el-cascader
            v-model="search.params"
            ref="cascader"
            placeholder="选择参数类型"
            size="small"
            :options="options"
            :props="cascaderProps"
            style="width:240px"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item prop="devSnArray" :show-message="false">
          <el-select
            v-show="selectToggle"
            v-model="search.devSnArray"
            placeholder="选择机台"
            size="small"
            multiple
            clearable
            class="mul-selection"
            popper-class="mul-select"
            collapse-tags
            :popper-append-to-body="false"
          >
            <el-option
              v-for="(item, index) in equipOption"
              :key="index"
              :label="search.gongxu + item.key_value + '号'"
              :value="item.key_value"
            ></el-option>
          </el-select>
          <div class="select-range" v-show="!selectToggle">
            <span class="label">车台范围：</span>
            <div v-for="(item, i) in range" :key="i">
              <span v-if="i !== 0">;</span>
              <el-input-number
                v-model="item.min"
                size="small"
                :controls="false"
                :min="0"
                :max="maxDev"
              />
              <span>-</span>
              <el-input-number
                v-model="item.max"
                size="small"
                :controls="false"
                :min="0"
                :max="maxDev"
              />
              <span
                class="icon"
                v-if="i !== 0"
                @click="clearInput(i)"
                style="font-size:12px;color:#666;margin:0 4px 0 0"
                ><i class="el-icon-circle-close"
              /></span>
            </div>
            <el-divider direction="vertical"></el-divider>
            <span class="icon" title="增加车台范围选择" @click="addRange">
              <i class="el-icon-plus" />
            </span>
          </div>
        </el-form-item>
        <el-button
          type="text"
          size="small"
          @click="selectToggle = !selectToggle"
          style="margin:0 20px 0 -10px"
          v-text="selectToggle ? '选择范围' : '选择机台'"
        />
        <el-form-item class="btn-list">
          <el-button type="primary" size="small" @click="getData"
            >查询</el-button
          >
          <el-button size="small" icon="el-icon-folder-add" @click="exportData"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
      <div class="data-table" ref="table">
        <el-table
          :data="tableData"
          style="width: 100%"
          :max-height="tableHeight"
        >
          <el-table-column prop="devSn" label="车台" align="center" />
          <el-table-column
            v-for="(item, index) in columns"
            :key="index"
            :label="item.label"
            align="center"
          >
            <template v-for="(column, i) in item.children">
              <el-table-column
                :prop="column.value"
                :label="column.label"
                :key="i"
                align="center"
                width="100"
              ></el-table-column>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="common-pagination">
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :page-size="search.size"
          :current-page.sync="search.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getSysDict,
  getParams1,
  getParams2,
  getSysDictByName
} from '@/api/common';
import { getActualData } from '@/api/workshop';
export default {
  data() {
    return {
      tableHeight: 200,
      search: {
        org: '',
        cj: '',
        gongxu: '',
        params: '',
        devSnArray: [],
        page: 1,
        size: 10
      },
      searchRules: {
        gongxu: [{ required: true, message: '请选择工序', trigger: 'change' }],
        params: [
          { required: true, message: '请选择参数类型', trigger: 'change' }
        ]
        // devSnArray: [
        //   { required: true, message: '请选择机台', trigger: 'change' }
        // ]
      },
      equipOption: [],
      total: 10,
      tableData: [],
      selectToggle: true,
      maxDev: 120,
      columns: [],
      range: [{ min: 0, max: 0 }],
      cascaderProps: {
        lazy: true,
        multiple: true,
        label: 'label',
        lazyLoad: async (node, resolve) => {
          if (node.level) {
            let form = {
              gongxu: node.data.gongxu,
              cs_type: node.data.cs_type
            };
            const { data } = await getParams2(form);
            data.map(item => {
              item.label = item['cs_name'];
              item.value = item['cs'];
              item.leaf = true;
            });
            resolve(data);
          }
        }
      },
      options: []
    };
  },
  computed: {
    cjOption() {
      return this.$store.getters.cjOption;
    },
    orgOption() {
      return this.$store.getters.orgOption;
    },
    gxOption() {
      return this.$store.getters.gxOption;
    }
  },
  watch: {
    selectToggle: function(val) {
      if (val) {
        let arr = [];
        this.range.map(item => {
          if (item.max - item.min > 0) {
            for (let i = item.min; i <= item.max; i++) {
              if (i) {
                arr.push(String(i));
              }
            }
          } else if (item.max - item.min == 0) {
            if (item.max !== 0) {
              arr.push(String(item.max));
            }
          }
        });
        this.search.devSnArray = arr;
      } else {
        let arr = this.getSeiresDevsn(this.search.devSnArray);
        if (arr.length == 0) {
          this.range = [{ min: 0, max: 0 }];
        } else {
          this.range = arr;
        }
      }
    }
  },
  created() {
    window.addEventListener('resize', this.getHeight);
  },
  mounted() {
    document.getElementsByClassName(
      'el-pagination__jump'
    )[0].childNodes[0].nodeValue = '跳至';
    this.$nextTick(() => {
      this.getHeight();
    });
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight);
  },
  methods: {
    async getEquip(val) {
      const equipData = await getSysDict(val);
      this.equipOption = equipData.data.dataList;
    },
    async getParams(val) {
      const { data } = await getParams1({ gongxu: val });
      let arr = [];
      data.map(item => {
        let obj = Object.assign({}, item);
        obj.label = item.cs_type;
        obj.value = item.cs_type;
        arr.push(obj);
      });
      this.options = arr;
    },
    getTableData() {
      this.$refs['search'].validate(async (valid, object) => {
        if (valid) {
          // 获取动态的列表表头
          let checked = this.$refs.cascader.getCheckedNodes(true);
          let columns = [];
          checked.map(item => {
            if (item.level == 2) {
              let findindex = null;
              let find = columns.find((param, index) => {
                if (param.label == item.parent.value) {
                  findindex = index;
                  return param.label == item.parent.value;
                }
              });
              if (!find) {
                let data = {
                  label: item.parent.value,
                  children: [
                    {
                      label: item.label,
                      value: item.value
                    }
                  ]
                };
                columns.push(data);
              } else {
                columns[findindex]['children'].push({
                  label: item.label,
                  value: item.value
                });
              }
            } else {
              columns.push({
                label: item.label,
                value: item.value
              });
            }
          });
          this.columns = columns;
          // 构建请求参数
          if (!this.selectToggle) {
            let arr = [];
            this.range.map(item => {
              if (item.max - item.min > 0) {
                for (let i = item.min; i <= item.max; i++) {
                  if (i) {
                    arr.push(String(i));
                  }
                }
              } else if (item.max - item.min == 0) {
                if (item.max !== 0) {
                  arr.push(String(item.max));
                }
              }
            });
            this.search.devSnArray = arr;
          }
          let form = Object.assign({}, this.search);
          for (let i in form) {
            if (form[i] == '') {
              delete form[i];
            }
          }
          delete form['params'];
          form.page = this.search.page - 1;
          const res = await getActualData(form);
          if (res.code == 1) {
            this.tableData = res.data;
            this.total = res.total;
          }
        } else {
          this.$message({
            message: '请选择工序、参数类型、机台！',
            iconClass: 'el-icon-warning',
            customClass: 'common-message'
          });
          return false;
        }
      });
    },
    async changeGX(val) {
      this.getParams(val);
      this.search.devSn = [];
      if (val) {
        const res = await getSysDictByName(val + '设备');
        if (res.code == 1) {
          let bh = res.data.dataList[0]['bh'];
          this.getEquip(bh);
        }
      } else {
        this.equipOption = [];
      }
    },
    exportData() {},
    getHeight() {
      this.tableHeight = this.$refs.table.offsetHeight;
    },
    addRange() {
      this.range.push({ min: null, max: null });
    },
    clearInput(index) {
      this.range.splice(index, 1);
    },
    getSeiresDevsn(arr) {
      var result = [],
        i = 0,
        str = [];
      if (arr.length > 0) {
        arr.sort(function(a, b) {
          return Number(a) - Number(b);
        });
        result[i] = [arr[0]];
        arr.reduce(function(prev, cur) {
          parseInt(cur) - parseInt(prev) === 1
            ? result[i].push(cur)
            : (result[++i] = [cur]);
          return cur;
        });
        result.map(item => {
          let obj = [].concat(item);
          if (item.length > 1) {
            str.push({ min: obj[0], max: obj[obj.length - 1] });
          } else if (item.length == 1) {
            str.push({ min: obj[0], max: obj[0] });
          }
        });
      }
      return str;
    },
    getData() {
      this.search.page = 1;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.search.page = 1;
      this.search.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.search.page = val;
      this.getTableData();
    }
  }
};
</script>

<style lang="scss" scoped>
.common-wrapper {
  height: 100%;
}
.common-search {
  display: flex;
  ::v-deep .btn-list .el-form-item__content {
    display: flex;
  }
}
.data-table {
  height: calc(100% - 110px);
  ::v-deep.el-table {
    font-size: 13px;
    th {
      background-color: #f8f9fb !important;
      color: #292b3d;
      font-weight: 500;
      padding: 9px 0;
    }
    .el-table__cell {
      padding: 10px 0;
    }
  }
}
</style>
<style lang="scss">
.select-range {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 13px;
  line-height:34px;
  .label {
    white-space: nowrap;
  }
  .el-input-number {
    width: 30px;
    .el-input__inner {
      border: none;
      text-align: center;
      padding: 0 5px !important;
      font-size: 12px;
    }
  }
  & > div {
    display: flex;
    flex-wrap: nowrap;
  }
  .icon {
    cursor: pointer;
    font-size: 16px;
    margin-left: 5px;
  }
}
</style>
